package admin

import (
	"github.com/labstack/echo"
	"github.com/sirupsen/logrus"
	"net/http"
	"src/config"
	"src/controller/param"
	"src/model"
	"src/util/context"
	"src/util/log"
)

var adminapplicationLogger = log.GetLogger()

func writeadminapplicationLoggerLog(funcName, errMsg string, err error) {
	adminapplicationLogger.WithFields(logrus.Fields{
		"package":  config.LogMessage + "/admin",
		"file":     "application.go",
		"function": funcName,
		"err":      err,
	}).Warn(errMsg)
}

func GetApplication(c echo.Context) error {
	id := context.GetJWTUsername(c)
	_, err := model.FindAdmin(id)
	if err != nil {
		writeadminapplicationLoggerLog("GetApplication", "1", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.Hasnotpower)
	}
	resData := map[string]interface{}{}
	resData["Application"], err = model.GetApplication()
	if err != nil {
		writeadminapplicationLoggerLog("GetApplication", "2", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorApplicationGet)
	}
	return context.RetData(c, resData)
}

func AgreeApplication(c echo.Context) error {
	id := context.GetJWTUsername(c)
	_, err := model.FindAdmin(id)
	if err != nil {
		writeadminapplicationLoggerLog("AgreeApplication", "1", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.Hasnotpower)
	}

	Application := new(param.ApplicationParam)
	err = c.Bind(&Application)
	if err != nil {
		writeadminapplicationLoggerLog("AgreeApplication", "2", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}
	err = model.ChangeType(Application.Id, Application.Tags)
	if err != nil {
		writeadminapplicationLoggerLog("AgreeApplication", "3", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorForumpostTypeChange)
	}
	err = model.ReadApplication(Application.Id)
	if err != nil {
		writeadminapplicationLoggerLog("AgreeApplication", "4", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorApplicationRead)
	}

	return context.RetData(c, "")
}

func DisagreeApplication(c echo.Context) error {
	id := context.GetJWTUsername(c)
	_, err := model.FindAdmin(id)
	if err != nil {
		writeadminapplicationLoggerLog("DisagreeApplication", "1", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.Hasnotpower)
	}
	Application := new(param.ApplicationParam)
	err = c.Bind(&Application)
	if err != nil {
		writeadminapplicationLoggerLog("DisagreeApplication", "2", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}

	err = model.ReadApplication(Application.Id)
	if err != nil {
		writeadminapplicationLoggerLog("DisagreeApplication", "3", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorApplicationRead)
	}

	return context.RetData(c, "")

}
